package model

import (
	"errors"
	"haodayizhi/global"

	"gorm.io/gorm"
)

const TableNameUserRole = "user_roles"

// UserRole mapped from table <user_roles>
type UserRole struct {
	UserID int64 `gorm:"column:user_id;type:bigint;primaryKey" json:"userId"`
	RoleID int64 `gorm:"column:role_id;type:bigint;primaryKey" json:"roleId"`
}

// TableName UserRole's table name
func (*UserRole) TableName() string {
	return TableNameUserRole
}

// CreateUserRole creates a new UserRole in the database.
func (m *UserRole) CreateUserRole() error {
	if err := global.Db.Create(m).Error; err != nil {
		return err
	}
	return nil
}

// GetUserRoleByID retrieves a UserRole by its ID from the database.
func (m *UserRole) GetUserRoleByID(id int64) (*UserRole, error) {
	result := global.Db.First(m, id)
	if result.Error != nil {
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			return nil, nil // UserRole not found
		}
		return nil, result.Error
	}
	return m, nil
}

// UpdateUserRole updates an existing UserRole in the database.
func (m *UserRole) UpdateUserRole() error {
	if err := global.Db.Save(m).Error; err != nil {
		return err
	}
	return nil
}

// DeleteUserRole deletes a UserRole by its ID from the database.
func (m *UserRole) DeleteUserRole(id int64) error {
	if err := global.Db.Delete(m, id).Error; err != nil {
		return err
	}
	return nil
}
